import {Component, OnInit} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {ModalController} from '@ionic/angular';
import {EquipmenthelpComponent} from '../../common/helpcenter/equipmenthelp/equipmenthelp.component';
import {FaulttypehelpComponent} from '../../common/helpcenter/faulttypehelp/faulttypehelp.component';
import {FaultlevelhelpComponent} from '../../common/helpcenter/faultlevelhelp/faultlevelhelp.component';
import {PickerRef, PickerService, ToastService} from 'ng-zorro-antd-mobile';
import {FaultcausehelpComponent} from '../../common/helpcenter/faultcausehelp/faultcausehelp.component';
import {RegistranthelpComponent} from '../../common/helpcenter/registranthelp/registranthelp.component';
import {DatePipe} from '@angular/common';
import {EquipmentfaultService} from './service/equipmentfault.service';

const data = [
    {
        url: 'assets/src/img/product1.png'
    },
    {
        url: 'assets/src/img/product2.png'
    }
];

@Component({
    selector: 'app-malfunction-repair',
    templateUrl: './malfunction-repair.page.html',
    styleUrls: ['./malfunction-repair.page.less'],
    providers: [DatePipe]
})
export class MalfunctionRepairPage implements OnInit {

    constructor(
        private _picker: PickerService,
        private _toast: ToastService,
        private datePipe: DatePipe,
        private formBuilder: FormBuilder,
        public modalController: ModalController,
        private equipmentfaultService: EquipmentfaultService,
    ) {
    }


    registerForm: FormGroup;

    formData;

    // formData: any = {
    //     product: 'LAM系列（6级）三相异步电机',
    //     number: 'CCBH001',
    //     code: 'AABBBCCCDD123',
    //     processUnit: '自动赋值',
    //     applyUnit: '中铁盾构集团',
    //     applyUser: '自动赋值',
    //     applyMobile: '',
    //     address: '',
    //     description: '',
    // };

    index = 0;
    // "我的报修"页面显示的数据
    myFaultList = [
        // {
        //     'myProduct': 'LAM系列（6级）三相异步电机',
        //     'myNumber': 'CCBH001',
        //     'myCode': 'AABBBCCCDD123',
        //     'myProcessUnit': '中铁盾构集团维修部',
        //     'myApplyUnit': '中铁盾构集团产品部',
        //     'myApplyUser': '张三',
        //     'myApplyMobile': '13112548586',
        //     'myAddress': '山东省济南市高新区',
        //     'myDescription': '发动机破损',
        //     'solve': true,
        //     'expand': true
        // }, {
        //     'myProduct': 'LAM系列（6级）三相异步电机',
        //     'myNumber': 'CCBH001',
        //     'myCode': 'AABBBCCCDD123',
        //     'myProcessUnit': '中铁盾构集团维修部',
        //     'myApplyUnit': '中铁盾构集团产品部',
        //     'myApplyUser': '张三',
        //     'myApplyMobile': '13112548586',
        //     'myAddress': '山东省济南市高新区',
        //     'myDescription': '发动机破损',
        //     'solve': false,
        //     'expand': false
        // }, {
        //     'myProduct': 'LAM系列（6级）三相异步电机',
        //     'myNumber': 'CCBH001',
        //     'myCode': 'AABBBCCCDD123',
        //     'myProcessUnit': '中铁盾构集团维修部',
        //     'myApplyUnit': '中铁盾构集团产品部',
        //     'myApplyUser': '张三',
        //     'myApplyMobile': '13112548586',
        //     'myAddress': '山东省济南市高新区',
        //     'myDescription': '发动机破损',
        //     'solve': true,
        //     'expand': false
        // }, {
        //     'myProduct': 'LAM系列（6级）三相异步电机',
        //     'myNumber': 'CCBH001',
        //     'myCode': 'AABBBCCCDD123',
        //     'myProcessUnit': '中铁盾构集团维修部',
        //     'myApplyUnit': '中铁盾构集团产品部',
        //     'myApplyUser': '张三',
        //     'myApplyMobile': '13112548586',
        //     'myAddress': '山东省济南市高新区',
        //     'myDescription': '发动机破损',
        //     'solve': false,
        //     'expand': false
        // }
    ];

    files = data.slice(0);
    multiple = false;

    showFaultState; // 页面显示的故障状态数据

    // 过滤条件
    filterParams = {
        sort: 'desc', // 排序-默认使用降序
        rows: 10, // 每页条数
        page: 1, // 当前页
        total: null, // 总页数
        code: null, // 故障单编号
        name: null, // 故障名称
        faultLevel: null, // 故障级别
        faultLocation: null, // 故障位置
        state: null, // 状态
        fuzzySearch: null, // 模糊搜索
        registrantid: null // 故障登记人
    };

    ngOnInit() {
        // 表单初始化
        this.buildForm();
    }

    // 获取“我的报修”列表数据
    getListDataByFilterParamsAndPageNumber(params) {

        this.equipmentfaultService.getEquipmentFaultListByFilterAndPage(params).then(res => {
            console.log('获取“我的报修”res=', res);
            // this.page = res['page'];
            // this.total = res['total'];
            // this.records = res['records'];
            // this.allTable = JSON.parse(JSON.stringify(res['rows']));
            this.myFaultList = this.addSolveProperty(JSON.parse(JSON.stringify(res['rows'])));

            // this.tempallTable = [];
            // this.tempTable = [];
            // this.loading = false;
            // this.operating = 'view';
            // this.selected = null;

        }, err => {
            this._toast.info('获取设备故障单信息列表失败');
            // this.message.info(this.translate.get('TEXT.BOAM.EQUIPMENTFAULT.GETDATAERROR'));
            // this.loading = false;
            // this.onResize();
        });
    }

    // 添加扩展收起属性
    addSolveProperty(oldList): any {
        const newList = JSON.parse(JSON.stringify(oldList));
        newList.map((item, index) => {
            if (index == 0) {
                item.expand = true;
            } else {
                item.expand = false;
            }
        });
        return newList;
    }

    // 手势左右滑动时触发
    onChange(item) {
        console.log('onChange', item);
        if (item.index == 1) {
            this.filterParams.registrantid = null;
            this.getListDataByFilterParamsAndPageNumber(this.filterParams);
        }

    }

    // 点击Tabs标签、手势左右滑动都会触发
    onTabClick(item) {
        console.log('onTabClick', item);
    }

    buildForm(): void {

        // this.registerForm = new FormGroup({
        //     product: new FormControl(this.formData.product, []),
        //     number: new FormControl(this.formData.number, []),
        //     code: new FormControl(this.formData.code, []),
        //     processUnit: new FormControl(this.formData.processUnit, []),
        //     applyUnit: new FormControl(this.formData.applyUnit, []),
        //     applyUser: new FormControl(this.formData.applyUser, []),
        //     applyMobile: new FormControl(this.formData.applyMobile, []),
        //     address: new FormControl(this.formData.address, []),
        //     description: new FormControl(this.formData.description, []),
        // });

        this.formData = this.formBuilder.group({
            id: [{value: null, disabled: false}],
            code: [{value: null, disabled: true}, Validators.required],      // 故障编号
            name: [{value: null, disabled: false}, Validators.required],     // 故障名称
            equipmentid: [{value: null, disabled: false}, Validators.required],       // 设备ID
            organizationid: [{value: null, disabled: false}], // 组织ID
            faulttype: [{value: null, disabled: false}, Validators.required],         // 故障类型
            faultlevel: [{value: null, disabled: false}, Validators.required],         // 故障级别
            faultLocation: [{value: null, disabled: false}, Validators.required],   // 故障部位
            state: [{value: null, disabled: false}, Validators.required],   //  故障状态, 0-蓝色，1-绿色
            note: [{value: null, disabled: false}],     // 备注
            faultcause: [{value: null, disabled: false}, Validators.required],  // 故障原因
            registrant: [{value: null, disabled: false}, Validators.required],  // 登记人
            discoveryTime: [{value: null, disabled: false}, Validators.required],   // 发现时间
            createtime: [{value: null, disabled: false}],  // 创建时间
            createuser: [{value: null, disabled: false}],  // 创建人
            lastmodifiedtime: [{value: null, disabled: false}],   // 最后修改时间
            lastmodifieduser: [{value: null, disabled: false}],   // 最后修改人
            dataVersion: [{value: null, disabled: false}], // 数据版本
        });


    }

    // 关联设备帮助
    async afterHelpAssociatedEquipment() {
        const modal = await this.modalController.create({
            component: EquipmenthelpComponent,
            showBackdrop: true,
            componentProps: {
                // 向组件传递的参数
                queryData: {id: '0020'}
            }
        });
        // 显示modal窗
        await modal.present();
        // 接收modal窗返回的数据
        await modal.onDidDismiss().then(event => {
            // 点击了 modal 窗的确定按钮
            if (event.data.callBackParameter) {
                this.formData.controls['equipmentid'].value = event.data.callBackParameter;
            } else {
                // 点击了 modal 窗的取消按钮，不对formData.equipmentid中的原有数据进行操作
            }
        });

    }

    // 故障类型帮助
    async afterHelpFaultType() {
        const modal = await this.modalController.create({
            component: FaulttypehelpComponent,
            showBackdrop: true,
            componentProps: {
                // 向组件传递的参数
                // queryData: null
            }
        });
        // 显示modal窗
        await modal.present();
        // 接收modal窗返回的数据
        await modal.onDidDismiss().then(event => {
            // 点击了 modal 窗的确定按钮
            if (event.data.callBackParameter) {
                this.formData.controls['faulttype'].value = event.data.callBackParameter;
            } else {
                // 点击了 modal 窗的取消按钮，不对formData.equipmentid中的原有数据进行操作
            }
        });

    }

    // 故障级别帮助
    async afterHelpFaultLevel() {
        const modal = await this.modalController.create({
            component: FaultlevelhelpComponent,
            showBackdrop: true,
            componentProps: {
                // 向组件传递的参数
                // queryData: null
            }
        });
        // 显示modal窗
        await modal.present();
        // 接收modal窗返回的数据
        await modal.onDidDismiss().then(event => {
            // 点击了 modal 窗的确定按钮
            if (event.data.callBackParameter) {
                this.formData.controls['faultlevel'].value = event.data.callBackParameter;
            } else {
                // 点击了 modal 窗的取消按钮，不对formData.equipmentid中的原有数据进行操作
            }
        });

    }

    // 故障状态帮助
    afterHelpFaultState() {
        const ref: PickerRef = this._picker.showPicker(
            {
                value: [],
                data: ['未处理', '处理中', '已处理']
            },
            (result) => {
                // console.log('result=', result);

                switch (result[0]) {
                    case '处理中':
                        this.showFaultState = '处理中';
                        this.formData.controls['state'].value = '1';
                        return;
                    case '已处理':
                        this.showFaultState = '已处理';
                        this.formData.controls['state'].value = '2';
                        return;
                    default:
                        this.showFaultState = '未处理';
                        this.formData.controls['state'].value = '0';
                        return;
                }

            },
            cancel => {
                // console.log('cancel');
            }
        );
        // console.log('this.formData.state = ', this.formData.state);
    }

    // 故障原因帮助
    async afterHelpFaultCause() {
        const modal = await this.modalController.create({
            component: FaultcausehelpComponent,
            showBackdrop: true,
            componentProps: {
                // 向组件传递的参数
                // queryData: null
            }
        });
        // 显示modal窗
        await modal.present();
        // 接收modal窗返回的数据
        await modal.onDidDismiss().then(event => {
            // 点击了 modal 窗的确定按钮
            if (event.data.callBackParameter) {
                this.formData.controls['faultcause'].value = event.data.callBackParameter;
            } else {
                // 点击了 modal 窗的取消按钮，不对formData.equipmentid中的原有数据进行操作
            }
        });

    }

    // 登记人帮助
    async afterHelpFaultRegistrant() {
        const modal = await this.modalController.create({
            component: RegistranthelpComponent,
            showBackdrop: true,
            componentProps: {
                // 向组件传递的参数
                // queryData: null
            }
        });
        // 显示modal窗
        await modal.present();
        // 接收modal窗返回的数据
        await modal.onDidDismiss().then(event => {
            // 点击了 modal 窗的确定按钮
            if (event.data.callBackParameter) {
                this.formData.controls['registrant'].value = event.data.callBackParameter;
            } else {
                // 点击了 modal 窗的取消按钮，不对formData.equipmentid中的原有数据进行操作
            }
        });

    }

    // 发现时间绑定的时间
    value = new Date();

    // 选中发现时间
    onOk(result: Date) {
        this.value = result;
        this.formData.controls['discoveryTime'].value = result;
    }

    currentDateFormat(date, format: string = 'yyyy-mm-dd HH:MM'): any {
        const pad = (n: number): string => (n < 10 ? `0${n}` : n.toString());
        return format
            .replace('yyyy', date.getFullYear())
            .replace('mm', pad(date.getMonth() + 1))
            .replace('dd', pad(date.getDate()))
            .replace('HH', pad(date.getHours()))
            .replace('MM', pad(date.getMinutes()))
            .replace('ss', pad(date.getSeconds()));
    }

    // 保存操作（校验数据格式、返回表单数据）
    saveOne() {
        console.log('保存');
        const data = this.formData.getRawValue();
        if (this.submitForm()) {// 将发现时间字段数据格式化
            data.discoveryTime = this.datePipe.transform(data.discoveryTime, 'yyyy-MM-dd HH:mm:ss');

            this.equipmentfaultService.saveOneData(data, null).then(res => {
                console.log('res = ', res);
            }, err => {
                console.log(' err = ', err);
            });

            // 获取所有值，包括禁用的控件,使用 this.formData.getRawValue()
            console.log('点击提交 this.formData.getRawValue() = ', this.formData.getRawValue());
            console.log('点击提交 data = ', data);
        }
    }

    // 非空校验
    faultTypeNonEmptyStatus: boolean; // 故障类型帮助
    faultLevelNonEmptyStatus: boolean; // 故障级别帮助
    faultCauseNonEmptyStatus: boolean; // 故障原因帮助
    equipmentNonEmptyStatus: boolean; // 关联设备帮助
    registrantNonEmptyStatus: boolean; // 登记人帮助

// 表单校验
    submitForm(): boolean {
        let cansave = true;
        for (const i in this.formData.controls) {
            this.formData.controls[i].markAsDirty();
            this.formData.controls[i].updateValueAndValidity();
            if (this.formData.controls[i].errors && this.formData.controls[i].errors.required) {
                cansave = false;
            }
            //  故障名称非空校验
            if (i == 'name') {
                // 该字段非空
                if (this.formData.controls[i].errors == null) {
                } else {
                    this.formData.controls[i].value = null;
                    this._toast.info('故障名称不能为空！', 500, null, null);
                    cansave = false;
                    return;
                }
            }
            //  关联设备非空校验
            if (i == 'equipmentid') {
                // 该字段非空
                if (this.formData.controls[i].errors == null) {
                    this.equipmentNonEmptyStatus = false;
                } else {
                    this.formData.controls[i].value = null;
                    this.equipmentNonEmptyStatus = true;
                    this._toast.info('报修产品不能为空！', 500, null, null);
                    cansave = false;
                    return;
                }
            }
            //  故障类型非空校验
            if (i == 'faulttype') {
                // 该字段非空
                if (this.formData.controls[i].errors == null) {
                    this.faultTypeNonEmptyStatus = false;
                } else {
                    this.formData.controls[i].value = null;
                    this.faultTypeNonEmptyStatus = true;
                    this._toast.info('故障类型不能为空！', 500, null, null);
                    cansave = false;
                    return;
                }
            }
            //  故障级别非空校验
            if (i == 'faultlevel') {
                // 该字段非空
                if (this.formData.controls[i].errors == null) {
                    this.faultLevelNonEmptyStatus = false;
                } else {
                    this.formData.controls[i].value = null;
                    this.faultLevelNonEmptyStatus = true;
                    this._toast.info('故障级别不能为空！', 500, null, null);
                    cansave = false;
                    return;
                }
            }
            //  故障原因非空校验
            if (i == 'faultcause') {
                // 该字段非空
                if (this.formData.controls[i].errors == null) {
                    this.faultCauseNonEmptyStatus = false;
                } else {
                    this.formData.controls[i].value = null;
                    this.faultCauseNonEmptyStatus = true;
                    this._toast.info('故障原因不能为空！', 500, null, null);
                    cansave = false;
                    return;
                }
            }
            //  登记人非空校验
            if (i == 'registrant') {
                // 该字段非空
                if (this.formData.controls[i].errors == null) {
                    this.registrantNonEmptyStatus = false;
                } else {
                    this.formData.controls[i].value = null;
                    this.registrantNonEmptyStatus = true;
                    this._toast.info('登记人不能为空！', 500, null, null);
                    cansave = false;
                    return;
                }
            }

        }
        return cansave;
    }


    //
    imageChange(params) {
        const {files, type, index} = params;
        this.files = files;
    }

    // 上传图片
    addImageClick(e) {
        e.preventDefault();
        this.files = this.files.concat({
            url: 'assets/src/img/product1.png'
        });
    }

    // 点击图片
    imageClick(params) {
        console.log(params);
    }

    expandChange(item: any, flag: boolean) {
        item.expand = !flag;
    }
}
